package com.king.nio.util;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * NIO 实现
 * @author taomk
 * @version 1.0
 * @since 15-1-25 上午11:41
 */
public class FileUtils {

	public static void nioCopyFile(String resource, String destination) throws IOException {
		FileInputStream fis = new FileInputStream(resource);
		FileOutputStream fos = new FileOutputStream(destination);

		// 读文件通道
		FileChannel readChannel = fis.getChannel();
		// 写文件通道
		FileChannel writeChannel = fos.getChannel();

		// 读入数据缓冲
		ByteBuffer buffer = ByteBuffer.allocate(1024);
		while (true) {
			buffer.clear();
			// 读入数据
			int len = readChannel.read(buffer);
			if (len == -1) {
				// 读取完毕
				break;
			}
			// 重置POSITION
			buffer.flip();
			// 写入文件
			writeChannel.write(buffer);
		}

	}
}
